<template>
  <div class="outsourcing-work-order">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>委外工单管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
        <el-form-item label="工单编号" prop="workOrderNumber">
          <el-input v-model="queryParams.workOrderNumber" placeholder="请输入工单编号" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="工单名称" prop="workOrderName">
          <el-input v-model="queryParams.workOrderName" placeholder="请输入工单名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="关联单号" prop="relatedOutsourcingNumber">
          <el-input v-model="queryParams.relatedOutsourcingNumber" placeholder="请输入关联单号" clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="委托单位" prop="entrustingUnit">
          <el-input v-model="queryParams.entrustingUnit" placeholder="请输入委托单位" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="未完成" value="未完成" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已确认" value="已确认" />
            <el-option label="生产中" value="生产中" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleDateRangeChange"
            style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd" :icon="Plus">
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" @click="handleExport" :icon="Download">
            导出
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column prop="workOrderNumber" label="工单编号" width="180" />
        <el-table-column prop="workOrderName" label="工单名称" width="200" />
        <el-table-column prop="relatedOutsourcingNumber" label="关联单号" width="180" />
        <el-table-column prop="documentDate" label="单据日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.documentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="entrustingUnit" label="委托单位" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="物品概要" width="200">
          <template #default="scope">
            <div class="item-summary-container">
              <span class="item-summary-text">{{ scope.row.itemSummary || '暂无物品' }}</span>
              <div class="item-summary-buttons">
                <el-button size="small" type="primary" @click="showProductionItems(scope.row)">
                  生产物品 ({{ getProductionItemsCount(scope.row) }}项)
                </el-button>
                <el-button size="small" type="success" @click="showConsumeItems(scope.row)">
                  消耗物品 ({{ getConsumeItemsCount(scope.row) }}项)
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" style="width: 50px;" type="primary" @click="handleEdit(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" style="width: 50px;" type="danger" @click="handleDelete(scope.row)" :icon="Delete">
              删除
            </el-button>
            <el-button size="small" style="width: 50px;" type="info" @click="handleView(scope.row)" :icon="View">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination v-model:current-page="queryParams.pageIndex" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="80%" :close-on-click-modal="false"
      :before-close="handleDialogClose">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px"
        style="max-height: 60vh; overflow-y: auto;">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <span class="section-title">基本信息</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工单编号" prop="workOrderNumber">
                <el-input v-model="formData.workOrderNumber" placeholder="请输入工单编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工单名称" prop="workOrderName">
                <el-input v-model="formData.workOrderName" placeholder="请输入工单名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联单号" prop="relatedOutsourcingId">
                <el-input v-model="formData.relatedOutsourcingNumber" placeholder="请选择生产单号" readonly
                  @click="openOutsourcingProcessingDialog">
                  <template #append>
                    <el-button @click="openOutsourcingProcessingDialog">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据日期" prop="documentDate">
                <el-date-picker v-model="formData.documentDate" type="date" placeholder="请选择单据日期" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="关联项目" prop="relatedProject">
                <el-select v-model="formData.relatedProject" placeholder="请选择项目名称" filterable style="width: 100%">
                  <el-option v-for="project in projectOptions" :key="project.id"
                    :label="`${project.projectName} (${project.projectNumber})`" :value="project.projectName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="委托单位" prop="entrustingUnit">
                <el-select v-model="formData.entrustingUnit" placeholder="请选择供应商" filterable style="width: 100%">
                  <el-option v-for="supplier in supplierOptions" :key="supplier.id" :label="supplier.supplierName"
                    :value="supplier.supplierName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="formData.contactPerson" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="负责人" prop="responsiblePerson">
                <el-input v-model="formData.responsiblePerson" placeholder="请输入负责人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部门" prop="department">
                <el-select v-model="formData.department" placeholder="请选择部门" filterable style="width: 100%">
                  <el-option v-for="department in departmentOptions" :key="department.id"
                    :label="department.departmentName" :value="department.departmentName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="未完成" value="未完成" />
                  <el-option label="进行中" value="进行中" />
                  <el-option label="已完成" value="已完成" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="formData.remarks" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 生产物品 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span class="section-title">生产物品</span>
              <el-button type="primary" size="small" @click="showProductionItemDialog">
                添加生产物品
              </el-button>
            </div>
          </template>
          <el-table :data="formData.productionItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeProductionItem(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 消耗物品 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span class="section-title">消耗物品</span>
              <el-button type="primary" size="small" @click="showConsumeItemDialog">
                添加消耗物品
              </el-button>
            </div>
          </template>
          <el-table :data="formData.consumeItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="warehouseId" label="仓库" width="100" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="number" label="实际数量" width="100" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeConsumeItem(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 附件管理 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-header">
              <span class="section-title">附件管理</span>
              <el-upload ref="uploadRef" :action="uploadAction" :headers="uploadHeaders" :data="uploadData"
                :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                :show-file-list="false" multiple accept="*/*">
                <el-button type="primary" size="small">上传附件</el-button>
              </el-upload>
            </div>
          </template>
          <el-table :data="formData.attachments" style="width: 100%">
            <el-table-column prop="fileName" label="文件名" width="200" />
            <el-table-column prop="fileSize" label="文件大小" width="100">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column prop="uploadDate" label="上传时间" width="150" />
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="downloadAttachment(scope.row)">
                  下载
                </el-button>
                <el-button size="small" type="danger" @click="removeAttachment(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="委外工单详情" width="80%" :close-on-click-modal="false">
      <div v-if="viewData">
        <!-- 基本信息 -->
        <el-card class="view-section" shadow="never">
          <template #header>
            <span class="section-title">基本信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工单编号">{{ viewData.workOrderNumber }}</el-descriptions-item>
            <el-descriptions-item label="工单名称">{{ viewData.workOrderName }}</el-descriptions-item>
            <el-descriptions-item label="关联单号">{{ viewData.relatedOutsourcingNumber }}</el-descriptions-item>
            <el-descriptions-item label="单据日期">{{ formatDate(viewData.documentDate) }}</el-descriptions-item>
            <el-descriptions-item label="关联项目">{{ viewData.relatedProject }}</el-descriptions-item>
            <el-descriptions-item label="委托单位">{{ viewData.entrustingUnit }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ viewData.contactPerson }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ viewData.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="负责人">{{ viewData.responsiblePerson }}</el-descriptions-item>
            <el-descriptions-item label="部门">{{ viewData.department }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(viewData.status)">{{ viewData.status }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注">{{ viewData.remarks }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 生产物品 -->
        <el-card class="view-section" shadow="never">
          <template #header>
            <span class="section-title">生产物品</span>
          </template>
          <el-table :data="viewData.productionItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-card>

        <!-- 消耗物品 -->
        <el-card class="view-section" shadow="never">
          <template #header>
            <span class="section-title">消耗物品</span>
          </template>
          <el-table :data="viewData.consumeItems" style="width: 100%">
            <el-table-column prop="itemCode" label="物品编码" width="120" />
            <el-table-column prop="itemName" label="物品名称" width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="warehouseId" label="仓库" width="100" />
            <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
            <el-table-column prop="number" label="实际数量" width="100" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </el-card>

        <!-- 附件 -->
        <el-card class="view-section" shadow="never">
          <template #header>
            <span class="section-title">附件</span>
          </template>
          <el-table :data="viewData.attachments" style="width: 100%">
            <el-table-column prop="fileName" label="文件名" width="200" />
            <el-table-column prop="fileSize" label="文件大小" width="100">
              <template #default="scope">
                {{ formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column prop="uploadDate" label="上传时间" width="150" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" type="primary" @click="downloadAttachment(scope.row)">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-dialog>

    <!-- 委外加工选择对话框 -->
    <el-dialog v-model="outsourcingProcessingDialogVisible" title="选择委外加工" width="80%">
      <el-form :inline="true" :model="outsourcingProcessingQuery" class="search-form">
        <el-form-item label="生产单号">
          <el-input v-model="outsourcingProcessingQuery.productionOrderNumber" placeholder="请输入生产单号" style="width: 200px" />
        </el-form-item>
        <el-form-item label="生产主题">
          <el-input v-model="outsourcingProcessingQuery.productionTheme" placeholder="请输入生产主题" style="width: 200px" />
        </el-form-item>
        <el-form-item label="委托单位">
          <el-input v-model="outsourcingProcessingQuery.entrustingUnit" placeholder="请输入委托单位" style="width: 200px" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="outsourcingProcessingQuery.contactPerson" placeholder="请输入联系人" style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="outsourcingProcessingQuery.status" placeholder="请选择状态" style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="未完成" value="未完成" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已确认" value="已确认" />
            <el-option label="生产中" value="生产中" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchOutsourcingProcessings">搜索</el-button>
          <el-button @click="resetOutsourcingProcessingQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="outsourcingProcessingLoading" :data="outsourcingProcessingData" @row-click="selectOutsourcingProcessing" style="width: 100%">
        <el-table-column prop="productionOrderNumber" label="生产单号" width="180" />
        <el-table-column prop="productionTheme" label="生产主题" width="200" />
        <el-table-column prop="entrustingUnit" label="委托单位" width="150" />
        <el-table-column prop="documentDate" label="生产日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.documentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="itemSummary" label="物品概要" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="selectOutsourcingProcessing(scope.row)">
              选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="outsourcingProcessingQuery.pageIndex" v-model:page-size="outsourcingProcessingQuery.pageSize"
        :page-sizes="[10, 20, 50]" :total="outsourcingProcessingTotal" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleOutsourcingProcessingSizeChange" @current-change="handleOutsourcingProcessingCurrentChange"
        style="margin-top: 20px; text-align: right" />
    </el-dialog>

    <!-- 物品选择对话框 -->
    <el-dialog v-model="itemDialogVisible" :title="itemDialogTitle" width="70%" :close-on-click-modal="false">
      <div class="item-dialog-content">
        <!-- 搜索条件 -->
        <el-form :model="itemQueryParams" :inline="true" label-width="100px" style="margin-bottom: 20px;">
          <el-form-item label="搜索关键词">
            <el-input v-model="itemQueryParams.SearchText" placeholder="请输入物品编码、名称或规格" style="width: 200px" />
          </el-form-item>
          <el-form-item label="物品类型">
            <el-select v-model="itemQueryParams.ItemType" placeholder="请选择物品类型" clearable style="width: 150px">
              <el-option label="原材料" value="原材料" />
              <el-option label="半成品" value="半成品" />
              <el-option label="成品" value="成品" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleItemSearch">搜索</el-button>
            <el-button @click="resetItemQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 物品列表 -->
        <el-table v-loading="itemLoading" :data="itemList" style="width: 100%"
          @selection-change="handleItemSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="itemCode" label="物品编码" width="120" />
          <el-table-column prop="itemName" label="物品名称" width="200" />
          <el-table-column prop="specification" label="规格型号" width="150" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="itemType" label="物品类型" width="100" />
          <el-table-column prop="brand" label="品牌" width="100" />
          <el-table-column prop="inventory" label="库存" width="80" />
        </el-table>

        <!-- 分页 -->
        <el-pagination v-model:current-page="itemQueryParams.pageIndex" v-model:page-size="itemQueryParams.pageSize"
          :page-sizes="[10, 20, 50]" :total="itemTotal" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleItemSizeChange" @current-change="handleItemCurrentChange"
          style="margin-top: 20px; text-align: right" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="itemDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="itemDialogTitle === '选择生产物品' ? confirmProductionItems() : confirmConsumeItems()">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 生产物品列表查看对话框 -->
    <el-dialog v-model="productionItemsDialogVisible" title="生产物品列表" width="80%">
      <el-table :data="currentProductionItems" style="width: 100%">
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="物品类型" width="100" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100" />
        <el-table-column prop="salePrice" label="销售价" width="100" />
        <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
        <el-table-column prop="remark" label="备注" width="150" />
      </el-table>
    </el-dialog>

    <!-- 消耗物品列表查看对话框 -->
    <el-dialog v-model="consumeItemsDialogVisible" title="消耗物品列表" width="80%">
      <el-table :data="currentConsumeItems" style="width: 100%">
        <el-table-column prop="itemCode" label="物品编码" width="120" />
        <el-table-column prop="itemName" label="物品名称" width="150" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="itemType" label="物品类型" width="100" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column prop="inventory" label="库存" width="80" />
        <el-table-column prop="purchasePrice" label="采购价" width="100" />
        <el-table-column prop="salePrice" label="销售价" width="100" />
        <el-table-column prop="manufacturerModel" label="制造商型号" width="120" />
        <el-table-column prop="warehouseId" label="仓库" width="100" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" />
        <el-table-column prop="number" label="实际数量" width="100" />
        <el-table-column prop="remark" label="备注" width="150" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, Delete, View } from '@element-plus/icons-vue'
import {
  getOutsourcingWorkOrderList,
  getOutsourcingWorkOrderById,
  addOutsourcingWorkOrder,
  updateOutsourcingWorkOrder,
  deleteOutsourcingWorkOrder,
  getOutsourcingProcessings,
  getItemsByOutsourcingProcessing,
  getAllItemsForWorkOrder,
  updateOutsourcingWorkOrderStatus,
  getOutsourcingWorkOrderAttachments,
  addOutsourcingWorkOrderAttachment,
  deleteOutsourcingWorkOrderAttachment,
  getSuppliers,
  getProjects,
  GetAllDepartments
} from '@/Https/server'
import * as XLSX from 'xlsx'
import type {
  OutsourcingWorkOrderDTO,
  OutsourcingWorkOrderShowDTO,
  APIResponse,
  APIPageing,
  OutsourcingProcessingDTO,
  ItemDTO
} from '@/types/outsourcingWorkOrder'

// 响应式数据
const loading = ref(false)
const tableData = ref<OutsourcingWorkOrderDTO[]>([])
const total = ref(0)
const dateRange = ref<string[]>([])
const selectedRows = ref<OutsourcingWorkOrderDTO[]>([])

// 查询参数
const queryParams = reactive<OutsourcingWorkOrderShowDTO>({
  pageIndex: 1,
  pageSize: 10,
  workOrderNumber: '',
  workOrderName: '',
  relatedOutsourcingNumber: '',
  entrustingUnit: '',
  contactPerson: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增委外工单')
const formRef = ref<FormInstance>()
const formData = reactive({
  id: 0,
  workOrderNumber: '',
  workOrderName: '',
  relatedOutsourcingId: 0,
  relatedOutsourcingNumber: '',
  documentDate: '',
  relatedProject: '',
  entrustingUnit: '',
  contactPerson: '',
  contactPhone: '',
  responsiblePerson: '',
  department: '',
  status: '未完成',
  remarks: '',
  productionItems: [] as any[],
  consumeItems: [] as any[],
  attachments: [] as any[]
})
const formRules = reactive<FormRules>({
  workOrderNumber: [{ required: true, message: '请输入工单编号', trigger: 'blur' }],
  workOrderName: [{ required: true, message: '请输入工单名称', trigger: 'blur' }],
  documentDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
  entrustingUnit: [{ required: true, message: '请选择委托单位', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})
const submitLoading = ref(false)

// 查看详情对话框
const viewDialogVisible = ref(false)
const viewData = ref<OutsourcingWorkOrderDTO | null>(null)

// 委外加工选项
const outsourcingOptions = ref<OutsourcingProcessingDTO[]>([])
const outsourcingLoading = ref(false)

// 委外加工选择对话框
const outsourcingProcessingDialogVisible = ref(false)
const outsourcingProcessingData = ref<OutsourcingProcessingDTO[]>([])
const outsourcingProcessingTotal = ref(0)
const outsourcingProcessingLoading = ref(false)
const outsourcingProcessingQuery = reactive({
  pageIndex: 1,
  pageSize: 10,
  productionOrderNumber: '',
  productionTheme: '',
  entrustingUnit: '',
  contactPerson: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 供应商、项目和部门选项
const supplierOptions = ref<any[]>([])
const projectOptions = ref<any[]>([])
const departmentOptions = ref<any[]>([])

// 物品选择对话框
const itemDialogVisible = ref(false)
const itemDialogTitle = ref('选择物品')
const itemQueryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  SearchText: '',
  ItemType: ''
})
const itemList = ref<ItemDTO[]>([])
const itemLoading = ref(false)
const itemTotal = ref(0)
const selectedItems = ref<ItemDTO[]>([])

// 物品列表查看对话框
const productionItemsDialogVisible = ref(false)
const consumeItemsDialogVisible = ref(false)
const currentProductionItems = ref<any[]>([])
const currentConsumeItems = ref<any[]>([])

// 物品数量缓存
const itemCountCache = ref<Map<number, { production: number, consume: number }>>(new Map())

// 方法
const formatDate = (date: string | Date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '未完成': 'warning',
    '已完成': 'success',
    '已确认': 'primary',
    '生产中': 'info',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const response:any = await getOutsourcingWorkOrderList(queryParams)
    if (response.code === 200) {
      console.log('委外工单列表数据:', response.data.pageData)
      tableData.value = response.data.pageData || []
      total.value = response.data.totalCount || 0
    } else {
      ElMessage.error(response.message || '获取列表失败')
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

// 查询相关方法
const handleDateRangeChange = (val: string[] | null) => {
  if (val) {
    queryParams.startDate = val[0]
    queryParams.endDate = val[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
}

const handleQuery = () => {
  queryParams.pageIndex = 1
  fetchList()
}

const handleReset = () => {
  Object.assign(queryParams, {
    pageIndex: 1,
    pageSize: 10,
    workOrderNumber: '',
    workOrderName: '',
    relatedOutsourcingNumber: '',
    entrustingUnit: '',
    contactPerson: '',
    status: '',
    startDate: '',
    endDate: ''
  })
  dateRange.value = []
  fetchList()
}

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.pageIndex = 1
  fetchList()
}

const handleCurrentChange = (page: number) => {
  queryParams.pageIndex = page
  fetchList()
}

const handleSelectionChange = (selection: OutsourcingWorkOrderDTO[]) => {
  selectedRows.value = selection
}

// 操作相关方法
const handleAdd = () => {
  dialogTitle.value = '新增委外工单'
  formData.id = 0 // 新增时清空ID
  formData.productionItems = []
  formData.consumeItems = []
  formData.attachments = []
  uploadData.entityId = '' // 新增时清空entityId
  formRef.value?.resetFields()
  dialogVisible.value = true
}

const handleEdit = async (row: OutsourcingWorkOrderDTO) => {
  try {
    const response:any = await getOutsourcingWorkOrderById({ id: row.id })
    if (response.code === 200) {
      const data = response.data
      console.log('编辑API返回数据:', data)
      console.log('编辑生产物品数据:', data.productionItems)
      console.log('编辑消耗物品数据:', data.consumeItems)
      formData.id = data.id
      formData.workOrderNumber = data.workOrderNumber
      formData.workOrderName = data.workOrderName
      formData.relatedOutsourcingId = data.relatedOutsourcingId || 0
      formData.relatedOutsourcingNumber = data.relatedOutsourcingNumber || ''
      formData.documentDate = data.documentDate
      formData.relatedProject = data.relatedProject || ''
      formData.entrustingUnit = data.entrustingUnit || ''
      formData.contactPerson = data.contactPerson || ''
      formData.contactPhone = data.contactPhone || ''
      formData.responsiblePerson = data.responsiblePerson || ''
      formData.department = data.department || ''
      formData.status = data.status || '未完成'
      formData.remarks = data.remarks || ''
      formData.productionItems = data.productionItems || []
      formData.consumeItems = data.consumeItems || []
      formData.attachments = data.attachments || []
      uploadData.entityId = data.id.toString() // 设置entityId为当前工单ID
      dialogTitle.value = '编辑委外工单'
      dialogVisible.value = true
    } else {
      ElMessage.error(response.data?.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleDelete = async (row: OutsourcingWorkOrderDTO) => {
  try {
    await ElMessageBox.confirm('确定要删除这条委外工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response:any = await deleteOutsourcingWorkOrder({ id: row.id })
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchList() // 刷新列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleView = async (row: OutsourcingWorkOrderDTO) => {
  try {
    const response:any = await getOutsourcingWorkOrderById({ id: row.id })
    if (response.code === 200) {
      console.log('查看详情API返回数据:', response.data)
      console.log('生产物品数据:', response.data.productionItems)
      console.log('消耗物品数据:', response.data.consumeItems)
      viewData.value = response.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleExport = async () => {
  try {
    // 获取所有数据（不分页）
    const exportParams = { ...queryParams, pageSize: 999999, pageIndex: 1 }
    const response: any = await getOutsourcingWorkOrderList(exportParams)
    
    if (response.code === 200) {
      const data = response.data.pageData || []
      
      // 准备导出数据
      const exportData = data.map((item: any, index: number) => ({
        '序号': index + 1,
        '工单编号': item.workOrderNumber || '',
        '工单名称': item.workOrderName || '',
        '关联单号': item.relatedOutsourcingNumber || '',
        '单据日期': item.documentDate ? new Date(item.documentDate).toLocaleDateString() : '',
        '委托单位': item.entrustingUnit || '',
        '联系人': item.contactPerson || '',
        '负责人': item.responsiblePerson || '',
        '状态': item.status || '',
        '物品概要': item.itemSummary || '',
        '备注': item.remarks || '',
        '创建时间': item.createTime ? new Date(item.createTime).toLocaleString() : ''
      }))
      
      // 创建工作簿
      const wb = XLSX.utils.book_new()
      const ws = XLSX.utils.json_to_sheet(exportData)
      
      // 设置列宽
      const colWidths = [
        { wch: 6 },  // 序号
        { wch: 15 }, // 工单编号
        { wch: 20 }, // 工单名称
        { wch: 15 }, // 关联单号
        { wch: 12 }, // 单据日期
        { wch: 15 }, // 委托单位
        { wch: 10 }, // 联系人
        { wch: 10 }, // 负责人
        { wch: 8 },  // 状态
        { wch: 25 }, // 物品概要
        { wch: 20 }, // 备注
        { wch: 20 }  // 创建时间
      ]
      ws['!cols'] = colWidths
      
      XLSX.utils.book_append_sheet(wb, ws, '委外工单数据')
      
      // 下载文件
      const fileName = `委外工单数据_${new Date().toLocaleDateString().replace(/\//g, '-')}.xlsx`
      XLSX.writeFile(wb, fileName)
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.message || '获取导出数据失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const showProductionItems = async (row: OutsourcingWorkOrderDTO) => {
  try {
    // 如果列表中没有物品数据，则通过API获取详情
    if (!row.productionItems || row.productionItems.length === 0) {
      const response: any = await getOutsourcingWorkOrderById({ id: row.id })
      if (response.code === 200) {
        currentProductionItems.value = response.data.productionItems || []
        // 更新缓存
        const productionCount = response.data.productionItems?.length || 0
        const consumeCount = response.data.consumeItems?.length || 0
        itemCountCache.value.set(row.id, { production: productionCount, consume: consumeCount })
      } else {
        ElMessage.error('获取生产物品数据失败')
        return
      }
    } else {
      currentProductionItems.value = row.productionItems
      // 更新缓存
      const productionCount = row.productionItems.length
      const consumeCount = row.consumeItems?.length || 0
      itemCountCache.value.set(row.id, { production: productionCount, consume: consumeCount })
    }
    productionItemsDialogVisible.value = true
  } catch (error) {
    console.error('获取生产物品失败:', error)
    ElMessage.error('获取生产物品失败')
  }
}

const showConsumeItems = async (row: OutsourcingWorkOrderDTO) => {
  try {
    // 如果列表中没有物品数据，则通过API获取详情
    if (!row.consumeItems || row.consumeItems.length === 0) {
      const response: any = await getOutsourcingWorkOrderById({ id: row.id })
      if (response.code === 200) {
        currentConsumeItems.value = response.data.consumeItems || []
        // 更新缓存
        const productionCount = response.data.productionItems?.length || 0
        const consumeCount = response.data.consumeItems?.length || 0
        itemCountCache.value.set(row.id, { production: productionCount, consume: consumeCount })
      } else {
        ElMessage.error('获取消耗物品数据失败')
        return
      }
    } else {
      currentConsumeItems.value = row.consumeItems
      // 更新缓存
      const productionCount = row.productionItems?.length || 0
      const consumeCount = row.consumeItems.length
      itemCountCache.value.set(row.id, { production: productionCount, consume: consumeCount })
    }
    consumeItemsDialogVisible.value = true
  } catch (error) {
    console.error('获取消耗物品失败:', error)
    ElMessage.error('获取消耗物品失败')
  }
}

// 获取生产物品数量
const getProductionItemsCount = (row: OutsourcingWorkOrderDTO) => {
  // 如果列表中有物品数据，直接返回数量
  if (row.productionItems && row.productionItems.length > 0) {
    return row.productionItems.length
  }
  
  // 从缓存中获取数量
  const cached = itemCountCache.value.get(row.id)
  if (cached) {
    return cached.production
  }
  
  // 如果没有缓存，返回问号
  return '?'
}

// 获取消耗物品数量
const getConsumeItemsCount = (row: OutsourcingWorkOrderDTO) => {
  // 如果列表中有物品数据，直接返回数量
  if (row.consumeItems && row.consumeItems.length > 0) {
    return row.consumeItems.length
  }
  
  // 从缓存中获取数量
  const cached = itemCountCache.value.get(row.id)
  if (cached) {
    return cached.consume
  }
  
  // 如果没有缓存，返回问号
  return '?'
}

// 新增/编辑对话框相关方法
const handleDialogClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        console.log('提交的表单数据:', formData)
        console.log('生产物品:', formData.productionItems)
        console.log('消耗物品:', formData.consumeItems)
        
        let response: any
        if (formData.id) {
          response = await updateOutsourcingWorkOrder(formData)
        } else {
          response = await addOutsourcingWorkOrder(formData)
        }
        if (response.code === 200) {
          ElMessage.success(formData.id ? '编辑成功' : '新增成功')
          // 如果是新增，设置返回的ID为entityId
          if (!formData.id && response.data && response.data.id) {
            formData.id = response.data.id
            uploadData.entityId = response.data.id.toString()
          }
          dialogVisible.value = false
          fetchList()
        } else {
          ElMessage.error(response.message || (formData.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 附件上传相关
const uploadRef = ref<any>(null)
const uploadAction = ref(import.meta.env.VITE_UploadAPP_API_URL + 'api/FileUpload/UploadFile') // 后端上传接口地址
const uploadHeaders = reactive({
  Authorization: `Bearer ${localStorage.getItem('token')}`
})
const uploadData = reactive({
  entityId: '',
  entityType: 'OutsourcingWorkOrder'
})

const beforeUpload = (rawFile: File) => {
  const isLt2M = rawFile.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过 2MB!')
  }
  return isLt2M
}

const handleUploadSuccess = (response: any, file: any) => {
  console.log('上传响应:', response)

  // 后端直接返回URL字符串，需要适配这种格式
  let fileUrl = ''
  if (typeof response === 'string') {
    fileUrl = response
  } else if (response.data) {
    fileUrl = response.data
  } else if (response.url) {
    fileUrl = response.url
  }

  if (fileUrl) {
    // 检查是否已经存在相同文件名的附件
    const existingAttachments = formData.attachments.filter(att => att.fileName === file.name)
    if (existingAttachments.length > 0) {
      ElMessage.warning(`文件 "${file.name}" 已存在，请勿重复上传`)
      return
    }

    const attachment = {
      fileName: file.name,
      fileSize: file.size,
      uploadDate: new Date().toLocaleString(),
      fileUrl: fileUrl,
      filePath: fileUrl,
      originalFileName: file.name,
      fileSizeBytes: file.size,
      fileType: file.type,
      fileExtension: file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
    }

    formData.attachments.push(attachment)
    ElMessage.success(`文件 "${file.name}" 上传成功`)
    console.log('附件已添加:', attachment)
  } else {
    ElMessage.error('上传响应格式错误')
    console.error('上传响应格式错误:', response)
  }
}

const handleUploadError = (error: any, file: any) => {
  console.error('上传失败:', error)
  ElMessage.error(`文件 "${file.name}" 上传失败: ${error.message || '网络错误'}`)
}

const downloadAttachment = async (attachment: any) => {
  try {
    if (attachment.fileUrl) {
      // 创建一个临时的a标签来下载文件
      const link = document.createElement('a')
      link.href = attachment.fileUrl
      link.download = attachment.fileName || 'download'
      link.target = '_blank'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage.success('开始下载文件')
    } else {
      ElMessage.warning('文件链接不可用')
    }
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

const removeAttachment = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除此附件吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const attachment = formData.attachments[index]
    if (attachment.id) {
      // 已保存的附件，调用删除API
      const response:any = await deleteOutsourcingWorkOrderAttachment({ id: attachment.id })
      if (response.code === 200) {
        ElMessage.success('删除成功')
        formData.attachments.splice(index, 1)
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } else {
      // 未保存的附件，直接从列表中移除
      formData.attachments.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除附件失败:', error)
      ElMessage.error('删除附件失败')
    }
  }
}

// 生产物品相关
const showProductionItemDialog = () => {
  if (!formData.relatedOutsourcingId) {
    ElMessage.warning('请先选择关联委外加工')
    return
  }
  itemDialogVisible.value = true
  itemDialogTitle.value = '选择生产物品'
  itemQueryParams.SearchText = ''
  itemQueryParams.ItemType = ''
  itemList.value = [] // 清空列表
  itemTotal.value = 0
  selectedItems.value = []
  searchProductionItems()
}



// 委外加工选择对话框相关方法
const openOutsourcingProcessingDialog = () => {
  outsourcingProcessingDialogVisible.value = true
  searchOutsourcingProcessings()
}

const searchOutsourcingProcessings = async () => {
  outsourcingProcessingLoading.value = true
  try {
    const response:any = await getOutsourcingProcessings(outsourcingProcessingQuery)
    if (response.code === 200) {
      outsourcingProcessingData.value = response.data.pageData || []
      outsourcingProcessingTotal.value = response.data.totalCount || 0
    } else {
      ElMessage.error(response.message || '搜索委外加工失败')
    }
  } catch (error) {
    console.error('搜索委外加工失败:', error)
    ElMessage.error('搜索委外加工失败')
  } finally {
    outsourcingProcessingLoading.value = false
  }
}

const resetOutsourcingProcessingQuery = () => {
  Object.assign(outsourcingProcessingQuery, {
    pageIndex: 1,
    pageSize: 10,
    productionOrderNumber: '',
    productionTheme: '',
    entrustingUnit: '',
    contactPerson: '',
    status: '',
    startDate: '',
    endDate: ''
  })
  searchOutsourcingProcessings()
}

const handleOutsourcingProcessingSizeChange = (size: number) => {
  outsourcingProcessingQuery.pageSize = size
  outsourcingProcessingQuery.pageIndex = 1
  searchOutsourcingProcessings()
}

const handleOutsourcingProcessingCurrentChange = (page: number) => {
  outsourcingProcessingQuery.pageIndex = page
  searchOutsourcingProcessings()
}

const selectOutsourcingProcessing = (row: OutsourcingProcessingDTO) => {
  console.log('选择委外加工:', row)
  formData.relatedOutsourcingId = row.id
  formData.relatedOutsourcingNumber = row.productionOrderNumber
  formData.entrustingUnit = row.entrustingUnit || ''
  formData.contactPerson = row.contactPerson || ''
  formData.contactPhone = row.contactPhone || ''
  formData.responsiblePerson = row.responsiblePerson || ''
  formData.department = row.department || ''
  formData.relatedProject = row.relatedProject || ''
  console.log('设置后的formData:', formData)
  outsourcingProcessingDialogVisible.value = false
}

// 获取供应商列表
const fetchSuppliers = async () => {
  try {
    const response:any = await getSuppliers({
      pageIndex: 1,
      pageSize: 1000, // 获取所有供应商
      searchText: '',
      supplierType: '',
      supplierStatus: 'Active' // 只获取活跃状态的供应商
    })
    if (response.code === 200) {
      supplierOptions.value = response.data.pageData
    } else {
      ElMessage.error(response.message || '获取供应商列表失败')
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
  }
}

// 获取项目列表
const fetchProjects = async () => {
  try {
    const response:any = await getProjects({
      pageIndex: 1,
      pageSize: 1000, // 获取所有项目
      searchText: '',
      projectStatus: '',
      category: ''
    })
    if (response.code === 200) {
      projectOptions.value = response.data.pageData
    } else {
      ElMessage.error(response.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  }
}

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response:any = await GetAllDepartments()
    if (response.code === 200) {
      departmentOptions.value = response.data
    } else {
      ElMessage.error(response.message || '获取部门列表失败')
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败')
  }
}





const handleProductionItemSelectionChange = (selection: ItemDTO[]) => {
  selectedItems.value = selection
}

const confirmProductionItemSelection = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择生产物品')
    return
  }
  formData.productionItems = selectedItems.value.map(item => ({
    ...item,
    plannedQuantity: 1, // 默认数量为1
    remark: '' // 默认备注为空
  }))
  itemDialogVisible.value = false
  ElMessage.success('生产物品选择成功')
}

const removeProductionItem = (index: number) => {
  formData.productionItems.splice(index, 1)
}

// 消耗物品相关
const showConsumeItemDialog = () => {
  itemDialogVisible.value = true
  itemDialogTitle.value = '选择消耗物品'
  itemQueryParams.SearchText = ''
  itemQueryParams.ItemType = ''
  itemList.value = [] // 清空列表
  itemTotal.value = 0
  selectedItems.value = []
  searchItems() // 调用搜索函数获取所有物品
}

const searchProductionItems = async () => {
  itemLoading.value = true
  try {
    console.log('委外加工ID:', formData.relatedOutsourcingId)
    const response:any = await getItemsByOutsourcingProcessing({
      outsourcingProcessingId: formData.relatedOutsourcingId,
      ...itemQueryParams
    })
    console.log('生产物品搜索响应:', response)
    if (response.code === 200) {
      itemList.value = response.data.pageData || []
      itemTotal.value = response.data.totalCount || 0
      console.log('生产物品列表:', itemList.value)
      
      // 如果没有数据，显示友好提示
      if (response.data.totalCount === 0) {
        ElMessage.info(response.message || '该委外加工暂无关联物品')
      }
    } else {
      ElMessage.error(response.message || '获取生产物品失败')
    }
  } catch (error) {
    console.error('获取生产物品失败:', error)
    ElMessage.error('获取生产物品失败')
  } finally {
    itemLoading.value = false
  }
}

const handleItemSearch = () => {
  // 根据对话框标题调用不同的搜索函数
  if (itemDialogTitle.value === '选择生产物品') {
    searchProductionItems()
  } else {
    searchItems()
  }
}

const searchItems = async () => {
  itemLoading.value = true
  try {
    console.log('搜索物品参数:', itemQueryParams)
    const response:any = await getAllItemsForWorkOrder(itemQueryParams)
    console.log('搜索物品响应:', response)
    if (response.code === 200) {
      itemList.value = response.data.pageData || []
      itemTotal.value = response.data.totalCount || 0
      console.log('物品列表:', itemList.value)
    } else {
      ElMessage.error(response.message || '搜索物品失败')
    }
  } catch (error) {
    console.error('搜索物品失败:', error)
    ElMessage.error('搜索物品失败')
  } finally {
    itemLoading.value = false
  }
}

const handleItemSelectionChange = (selection: ItemDTO[]) => {
  selectedItems.value = selection
}

const confirmProductionItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择生产物品')
    return
  }

  selectedItems.value.forEach(item => {
    const existingIndex = formData.productionItems.findIndex(p => p.itemId === item.id)
    if (existingIndex === -1) {
      formData.productionItems.push({
        itemId: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        specification: item.specification,
        unit: item.unit,
        itemType: item.itemType,
        itemClassification: '',
        brand: item.brand,
        plannedQuantity: 1,
        remark: ''
      })
    }
  })

  itemDialogVisible.value = false
  selectedItems.value = []
  ElMessage.success('生产物品选择成功')
}

const confirmConsumeItems = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择消耗物品')
    return
  }

  selectedItems.value.forEach(item => {
    const existingIndex = formData.consumeItems.findIndex(c => c.itemId === item.id)
    if (existingIndex === -1) {
      formData.consumeItems.push({
        itemId: item.id,
        itemCode: item.itemCode,
        itemName: item.itemName,
        specification: item.specification,
        unit: item.unit,
        itemType: item.itemType,
        itemClassification: '',
        brand: item.brand,
        inventory: item.inventory,
        warehouseId: '', // 字符串类型，存储仓库名称
        plannedQuantity: 1,
        number: 1,
        remark: ''
      })
    }
  })

  itemDialogVisible.value = false
  selectedItems.value = []
  ElMessage.success('消耗物品选择成功')
}

const removeConsumeItem = (index: number) => {
  formData.consumeItems.splice(index, 1)
}





// 物品选择分页相关
const handleItemSizeChange = (size: number) => {
  itemQueryParams.pageSize = size
  itemQueryParams.pageIndex = 1
  handleItemSearch()
}

const handleItemCurrentChange = (page: number) => {
  itemQueryParams.pageIndex = page
  handleItemSearch()
}

const resetItemQuery = () => {
  itemQueryParams.SearchText = ''
  itemQueryParams.ItemType = ''
  itemQueryParams.pageIndex = 1
  itemList.value = []
  itemTotal.value = 0
  handleItemSearch()
}

// 页面初始化
onMounted(() => {
  fetchList()
  fetchSuppliers() // 获取供应商列表
  fetchProjects() // 获取项目列表
  fetchDepartments() // 获取部门列表
})
</script>

<style scoped>
.outsourcing-work-order {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 物品概要样式 */
.item-summary-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-summary-text {
  font-weight: 500;
  color: #303133;
}

.item-summary-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-card__body) {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

/* 新增/编辑对话框样式 */
.form-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

/* 查看详情对话框样式 */
.view-section {
  margin-bottom: 20px;
}

.view-section .el-descriptions {
  margin-top: 15px;
}

.view-section .el-descriptions-item__label {
  font-weight: bold;
  color: #606266;
}

.view-section .el-descriptions-item__content {
  color: #909399;
}

.view-section .el-tag {
  margin-right: 5px;
}

/* 物品选择对话框样式 */
.item-dialog-content {
  padding: 20px;
}

.item-dialog-content .el-form {
  margin-bottom: 20px;
}

.item-dialog-content .el-table {
  margin-bottom: 20px;
}

.item-dialog-content .el-pagination {
  margin-top: 20px;
}

/* 物品概要样式 */
.item-summary-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-summary-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.4;
}

.item-summary-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.item-summary-buttons .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
  line-height: 1.2;
}

/* 物品查看对话框样式 */
.production-items-dialog .el-message-box__content,
.consume-items-dialog .el-message-box__content {
  max-width: 800px;
}

/* 表单验证样式 */
.el-form-item.is-error .el-input__inner {
  border-color: #f56c6c;
}

.el-form-item.is-error .el-textarea__inner {
  border-color: #f56c6c;
}

/* 按钮组样式 */
.operation-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 卡片阴影效果 */
.el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.el-card__header {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

/* 分页器样式 */
:deep(.el-pagination) {
  justify-content: flex-end;
  margin-top: 20px;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

/* 搜索表单样式 */
.search-card .el-form-item {
  margin-bottom: 15px;
}

.search-card .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 对话框内容滚动 */
.el-dialog__body {
  max-height: 70vh;
  overflow-y: auto;
}

/* 文件上传样式 */
:deep(.el-upload) {
  display: inline-block;
}

:deep(.el-upload-list) {
  margin-top: 10px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .outsourcing-work-order {
    padding: 10px;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .el-table {
    font-size: 12px;
  }
}
</style>